package com.zhiyou100.reflect;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class Demo4 {

    public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {

        Class<User> userClass = User.class;
        //获取所有的声明的构造方法
        Constructor<?>[] constructors = userClass.getDeclaredConstructors();
        for (Constructor<?> constructor : constructors) {
            int i = constructor.getModifiers();
            System.out.println("i = " + i);
        }
        //获取的是public修饰的构造
        Constructor<?>[] constructors1 = userClass.getConstructors();
        System.out.println(constructors1.length);   //2
        System.out.println("-------------------------------------");
        //根据形参类型获取对应的构造方法    getDeclaredConstructor  任意修饰符均可
        Constructor<User> constructor = userClass.getDeclaredConstructor(String.class);
        int count = constructor.getParameterCount();
        System.out.println("当前构造的形参个数 = " + count);
        Class<?>[] types = constructor.getExceptionTypes();
        for (Class<?> type : types) {
            System.out.println("当前构造的异常类型：" + type);
        }
        //动态的获取构造方法之后可以实例化对象,注意，私有构造通过反射实例化会出现异常
//        User user = constructor.newInstance("xueyin");
        Constructor<User> constructor1 = userClass.getDeclaredConstructor(String.class, int.class);
        User user = constructor1.newInstance("xueyin", 20);
        System.out.println("user = " + user);

    }
}
